<?php
namespace Modules\Activity\Entities\Lottery;

use Modules\Core\Entities\BaseEntity as Model;

class Ticket extends Model
{
	protected $guarded = [];
    static public $resourcename = '抽签号';
    protected $table = 'lottery_tickets';

    protected $casts = [
    ];

    public function scopeLucky($query)
    {
        return $query->where('status', 1);
    }

    // 记录此签号是谁赠送的
    public function invitee() 
    {
    	return $this->belongsTo('\Modules\User\Entities\User', 'invitee_id');
    }

    // 活动
    public function activity() 
    {
    	return $this->belongsTo('\Modules\Activity\Entities\Lottery\Activity', 'activity_id');
    }

    // 记录此签号中奖的sku
    public function package_sku() 
    {
    	return $this->belongsTo('\Modules\Asset\Entities\PackageSku', 'package_sku_id');
    }

    // 记录此签号实物领取的订单
    public function order() 
    {
    	return $this->belongsTo('\Modules\Activity\Entities\ActivityOrder', 'order_id');
    }

    public function generateNumber()
    {
        $number = 'T'. (12000  + $this->id);
        $this->update([
            'number' => $number
        ]);
    }

    static public function createWith($record, $user, $type, $options = [])
    {
        $typeMap = [
            'join' => 1,
            'invite' => 2,
            'box_reward' => 3,    // 抽盲盒赠送
        ];

        $item = self::create([
            'uuid' => uniqid(),
            'activity_record_id' => $record->id,
            'activity_id' => $record->activity_id,
            'session' => $record->session,
            'user_id' => $user->id,
            'source_type' => $typeMap[$type],
            'invitee_id' => @$options['invitee']->id,
            'order_id' => @$options['order']->id
        ]);

        $item->generateNumber();

        return $item;
    }
}
